using FytSoa.Application.Erp.Param;
using FytSoa.Common.Enum;
using FytSoa.Domain.Erp;
using FytSoa.Sugar;
using FytSoa.Common.Utils;
using FytSoa.Common.Param;
using FytSoa.Common.Result;
using Mapster;
using Microsoft.AspNetCore.Mvc;
using SqlSugar;

namespace FytSoa.Application.Erp;

/// <summary>
/// erp-生产品控驳回服务接口
/// </summary>
[ApiExplorerSettings(GroupName = "v9")]
public class ErpProduceRejectService : IApplicationService 
{
    private readonly SugarRepository<ErpProduceReject> _thisRepository;
    private readonly SugarRepository<ErpProduceOrder> _orderRepository;
    public ErpProduceRejectService(SugarRepository<ErpProduceReject> thisRepository
    ,SugarRepository<ErpProduceOrder> orderRepository)
    {
        _thisRepository = thisRepository;
        _orderRepository = orderRepository;
    }
    
    /// <summary>
    /// 查询所有
    /// </summary>
    /// <param name="param"></param>
    /// <returns></returns>
    public async Task<List<ErpProduceRejectDto>> GetListAsync(ErpProduceRejectSearchParam param)
    {
        var query = await _thisRepository.AsQueryable()
            .WhereIF(param.OrderId!=0,m=>m.OrderId==param.OrderId)
            .WhereIF(param.CraftId!=0,m=>m.RelationId==param.CraftId)
            .Includes(m=>m.Craft)
            .OrderByDescending(m => m.Id)
            .ToListAsync();
        return query.Adapt<List<ErpProduceRejectDto>>();
    }

    /// <summary>
    /// 根据主键查询
    /// </summary>
    /// <param name="id"></param>
    /// <returns></returns>
    [HttpGet("{id}")]
    public async Task<ErpProduceRejectDto> GetAsync(long id)
    {
        var model = await _thisRepository.GetByIdAsync(id);
        return model.Adapt<ErpProduceRejectDto>();
    }

    /// <summary>
    /// 添加
    /// </summary>
    /// <param name="model"></param>
    /// <returns></returns>
    public async Task<bool> AddAsync(ErpProduceRejectDto model) =>
        await _thisRepository.InsertAsync(model.Adapt<ErpProduceReject>());

    /// <summary>
    /// 修改
    /// </summary>
    /// <param name="model"></param>
    /// <returns></returns>
    [UnitOfWork]
    public async Task ModifyAsync(ErpProduceRejectDto model)
    {
        await _thisRepository.UpdateAsync(model.Adapt<ErpProduceReject>());
        //更新状态
        await _orderRepository.UpdateAsync(m => new ErpProduceOrder()
        {
            Phase = ErpProducePhaseEnum.QualityControl,
            ControlStatus = 0
        },m=>m.Id==model.OrderId);
    }

    /// <summary>
    /// 删除,支持批量
    /// </summary>
    /// <param name="ids"></param>
    /// <returns></returns>
    [HttpDelete]
    public async Task<bool> DeleteAsync([FromBody]List<long> ids) =>
        await _thisRepository.DeleteAsync(m=>ids.Contains(m.Id));
}
